package com.lsh.service.impl;

import com.lsh.dao.UserDao;
import com.lsh.dao.UserTokenDao;
import com.lsh.domain.User;
import com.lsh.domain.UserTokens;
import com.lsh.util.TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.lsh.service.LoginNewService;

/**
 * 登录模块实现类
 * @author Administrator
 * @date 2019/10/07 21:26
 */
@Service
public class LoginNewServiceImpl implements LoginNewService {

    @Autowired
    UserDao userDao;
    @Autowired
    UserTokenDao userTokenDao;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 校验登录验证码
     * @param code
     * @param cToken
     * @return
     */
    @Override
    public String checkCaptcha(String code, String cToken) {
        if(StringUtils.isEmpty(cToken)) return "验证码过期";
        String correctCode = (String) redisTemplate.opsForValue().get(cToken);
        if(!code.equals(correctCode)) return "验证码输入不正确";
        return null;
    }

    /**
     * 校验用户名和密码
     * @param username
     * @param password
     * @return
     */
    @Override
    public String checkUser(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setEmail(username);
        user.setMobile(username);
        user.setPassword(password);
        String result = userDao.getByUser(user);
        if(result == null) return null;
        return result;
    }

    /**
     * 更新服务器token并返回令牌
     * @param userId
     * @return
     */
    @Override
    public String resToken(String userId, String username) {
        String token = TokenUtil.buildToken(username);
        UserTokens userTokens = new UserTokens();
        userTokens.setUid(Integer.parseInt(userId));
        userTokens.setToken(token);
        userTokens.setStatus(1);
        int result = userTokenDao.updateUserToken(userTokens);
        if(result != 1) return null;
        return token;
    }
}
